package com.zhdl.modules.prefiresys.web.controller;

import com.zhdl.common.util.WebResult;
import com.zhdl.common.ytools.EnumHelper;
import com.zhdl.modules.prefiresys.entity.DetectorAreaInfo;
import com.zhdl.modules.prefiresys.service.DetectorAreaInfoService;
import com.zhdl.modules.prefiresys.task.CollectDetector;
import com.zhdl.modules.prefiresys.web.request.*;
import com.zhdl.modules.prefiresys.web.service.CollectService;
import com.zhdl.network.prefiretcp.before.MemDevice;
import com.zhdl.network.service.FireService;
import com.zhdl.network.service.dto.FireParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.*;

import static com.zhdl.AppApplication.localSoundStatus;
import static com.zhdl.modules.prefiresys.web.service.EventBusResult.allPara97;
import static com.zhdl.modules.prefiresys.web.service.EventBusResult.allPara9B;

/**
 * 通讯相关接口
 */
@RestController
@RequestMapping("/api/v1/com")
public class ComController {

    @Autowired
    private CollectService collectService;


    @Autowired
    private DetectorAreaInfoService detectorAreaInfoService;

    @Autowired
    private FireService fireService;



    /**
     * 获取探测器参数
     *
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @PostMapping("/get/detector/param")
    public WebResult<FireParameter> getDetectorParam(@RequestBody @Validated GetDetectorParamRequest request) throws IOException, InterruptedException {

//        // 异步执行的操作
//        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//            try {
//                // 模拟耗时操作
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return "异步操作结果";
//        });
//
//        // 获取异步操作的结果
//        String result = future.get();
//        return result;

        MemDevice device = collectService.getMemDevice(request.getDetectorId());
        if (device == null) {
            return WebResult.failResult("设备不存在");
        }
        /*
          获取探测器参数
         */
        fireService.getDetectorParam(device);

        // 创建一个核心线程数为5的线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50));

        // 创建一个计算任务
        Callable<FireParameter> myTask = () -> {
            Thread.sleep(1000);
            return allPara97;
        };

        Future<FireParameter> future = threadPoolExecutor.submit(myTask);

        try {
            FireParameter sum = future.get();
            return WebResult.okResult(sum);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置探测器参数
     *
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @PostMapping("/set/detector/param")
    public WebResult setDetectorPara(@RequestBody @Validated SetDetectorParamRequest request) throws IOException, InterruptedException {

        MemDevice device = collectService.getMemDevice(request.getDetectorId());

        if (device == null) {
            return WebResult.failResult("设备不存在");
        }

        /*
          设置探测器参数
         */
        fireService.setDetectorParam(request, device);

        StringBuilder sbLog = new StringBuilder();
        allPara9B.forEach((key, value) -> {
            if (value > 0)
                sbLog.append(String.format("%02X:%s", key, EnumHelper.getParamSetResultDesc(value)));
        });

        if (sbLog.isEmpty()) {
            // 设置成功
            return WebResult.okResult();
        } else {
            // 设置失败
            return WebResult.failResult(sbLog.toString());
        }
    }

    /**
     * 获取厂家参数
     *
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @PostMapping("/get/factory/param")
    public WebResult<FireParameter> getFactoryParam(@RequestBody @Validated GetFactoryParamRequest request) throws IOException, InterruptedException {
        MemDevice device = collectService.getMemDevice(request.getDetectorId());
        if (device == null)
            return WebResult.failResult("设备不存在");

        /*
          获取厂家参数
         */
        fireService.getDetectorParam(device);

        if (allPara97 == null)
            return WebResult.commNoAsk();
        return WebResult.okResult(allPara97);
    }

    /**
     * 设置厂家参数
     *
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @PostMapping("/set/factory/param")
    public WebResult setFactoryPara(@RequestBody @Validated SetFactoryParamRequest request) throws IOException, InterruptedException {

        MemDevice device = collectService.getMemDevice(request.getDetectorId());
        if (device == null)
            return WebResult.failResult("设备不存在");

        /**
         * 设置厂家参数
         */
        fireService.setFactoryParam(request, device);

        StringBuilder sbLog = new StringBuilder();
        allPara9B.forEach((key, value) -> {
            if (value > 0)
                sbLog.append(String.format("%02X:%s", key, EnumHelper.getParamSetResultDesc(value)));
        });

        if (sbLog.isEmpty()) {
            // 设置成功
            return WebResult.okResult();
        } else {
            // 设置失败
            return WebResult.failResult(sbLog.toString());
        }
    }

    /**
     * 获取数据监控数据
     *
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @GetMapping("/para/monitor")
    public WebResult<FireParameter> generalParamMonitor() throws IOException, InterruptedException {

        MemDevice device = collectService.getMemDevice("1");
        if (device == null) {
            return WebResult.failResult("设备不存在");
        }
        fireService.GeneralParamMonitor(device);

        return WebResult.okResult(new FireParameter());

    }

    /**
     *
     *
     * @param request
     * @return
     */
    @PostMapping(path = "clear/alarm")
    public WebResult<String> clearAlarm(@RequestBody @Validated ClearAlarmRequest request) throws IOException, InterruptedException {

//        固定密码为 132901
//        20230712
//        if (!request.getPwd().equals("26c0518a6508198645f16e61d5388ed7"))
//            return WebResult.failResult("密码不正确");
//
        DetectorAreaInfo detectorAreaInfo = detectorAreaInfoService.selectById(request.getAreaId());

        if (detectorAreaInfo == null)
            return WebResult.failResult("防区不存在");

        MemDevice device = collectService.getMemDevice(detectorAreaInfo.getDetectorId());

        if (device == null)
            return WebResult.failResult("设备不存在");

        fireService.setClearAlarm(device);

        return WebResult.okResult();
    }


    /**
     * 静音/取消静音 通知火前实现
     *
     * @param request
     * @return
     */
    @PostMapping(path = "ctrl/sound2")
    public WebResult newCtrlSound(@RequestBody @Validated CtrlSoundRequest request) throws IOException, InterruptedException {

        //调用静音同时关闭蜂鸣器声音
        DetectorAreaInfo detectorAreaInfo = detectorAreaInfoService.selectById(request.getAreaId());
        if (detectorAreaInfo == null)
            return WebResult.failResult("防区不存在");

        MemDevice device = collectService.getMemDevice(detectorAreaInfo.getDetectorId());
        if (device == null) {
            return WebResult.failResult("设备不存在");
        }

        fireService.setBeforeFireCtrlSound(device, request);

        // 设置成功
        return WebResult.okResult("静音成功");
    }

    @Resource
    private CollectDetector collectDetector;


    @GetMapping(path = "ctrl/soundLocalhost")
    public WebResult ctrlSoundLocal(boolean status) {
        localSoundStatus = status;
        // 设置成功
        return WebResult.okResult("静音成功");
    }



}
